import django_filters
from main.filters import NumberInFilter
from main.models import Contract
from main.permissions import DjangoModelFullPermissions
from rest_framework import serializers, viewsets


class ContractSerializer(serializers.ModelSerializer):
    creator = serializers.PrimaryKeyRelatedField(read_only=True, required=False)
    client = serializers.PrimaryKeyRelatedField(read_only=True, required=False)
    order = serializers.PrimaryKeyRelatedField(read_only=True, required=False)
    attachs = serializers.SerializerMethodField(read_only=True, required=False)

    def get_attachs(self, obj):
        return obj.attachs.count()

    class Meta:
        model = Contract
        fields = (
            "id",
            "number",
            "date",
            "amount_due",
            "amount_paid",
            "note",
            "created_on",
            "updated_on",
            "client",
            "order",
            "attachs",
        )


class ContractFilter(django_filters.FilterSet):
    ids = NumberInFilter(field_name="id", lookup_expr="in")

    class Meta:
        model = Contract
        fields = ("id",)


class ContractViewSet(viewsets.ModelViewSet):
    queryset = Contract.objects.all()
    serializer_class = ContractSerializer
    permission_classes = (DjangoModelFullPermissions,)
    filterset_class = ContractFilter
